package com.choosefine.springboot.devops.base.weixin;

import com.choosefine.springboot.devops.activity.dto.EwmTickedVO;
import com.choosefine.springboot.devops.activity.dto.TickedDto;
import com.choosefine.springboot.devops.activity.model.Activity;
import com.choosefine.springboot.devops.base.config.TokenUtil;
import com.choosefine.springboot.devops.base.result.RedisSerialize;
import com.choosefine.springboot.devops.base.serviceImpl.RedisServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2017/2/13 0013.
 */
public class Event {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RedisServiceImpl redisService;
    @Autowired
    private RestTemplate restTemplate;

    public void event(String url, HttpServletResponse response,Integer activity) throws IOException {
        String ticketUrl="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+ TokenUtil.getToken();
        String ewm="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";//二维码地址
        HttpHeaders httpHeaders=new HttpHeaders();
        MediaType type2 = MediaType.parseMediaType("application/json;charset=UTF-8");
        httpHeaders.setContentType(type2);
        httpHeaders.set("Accept",MediaType.APPLICATION_JSON_UTF8.toString());
        HttpEntity<String> requestEntity = new HttpEntity<String>(objectMapper.writeValueAsString(new TickedDto(redisMethodId(url,activity))), httpHeaders);
        ResponseEntity<EwmTickedVO> exchange =
                restTemplate.exchange(ticketUrl, HttpMethod.POST, requestEntity, new ParameterizedTypeReference<EwmTickedVO>() {});
        EwmTickedVO resut=exchange.getBody();
        response.sendRedirect(ewm+resut.getTicket());
    }


    private Integer redisMethodId(String url,Integer activity) throws IOException {
        String activityString=redisService.get("Activity"+activity);
        Activity activityObj=objectMapper.readValue(activityString,Activity.class);
        int redisId=(int)(Math.random()*100000);
        RedisSerialize param=new RedisSerialize();
        param.setId(redisId);
        param.setUrl(url);
        redisService.set(redisId+"",objectMapper.writeValueAsString(param));
        return redisId;
    }
}
